package com.lottery.im.module.chat.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.adapter.InviteGroupMemberAdapter;
import com.lottery.im.module.chat.presenter.InviteGroupMemberPresenter;
import com.lottery.im.module.chat.view.InviteGroupMemberView;
import com.lottery.im.module.tim.model.FriendProfile;
import com.lottery.im.module.tim.model.FriendshipInfo;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.group.TIMGroupManagerExt;
import com.tencent.imsdk.ext.group.TIMGroupMemberResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 邀请好友进群
 */
public class InviteGroupMemberFragment extends BaseSwipeFragment<InviteGroupMemberPresenter>
    implements InviteGroupMemberView {

  private final static String ID_KEY = "ID_KEY";

  public static InviteGroupMemberFragment create(String id) {
    InviteGroupMemberFragment fragment = new InviteGroupMemberFragment();
    Bundle b = new Bundle();
    b.putString(ID_KEY, id);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.iv_clear) ImageView mIvClear;
  @BindView(R.id.list) RecyclerView mList;
  @BindView(R.id.btn_confirm) Button mBtnConfirm;
  @BindView(R.id.et_search) EditText mEtSearch;
  @BindView(R.id.tv_empty_tip) TextView mTvEmptyTip;

  private String mGroupId;

  private List<String> mGroupMemberIds = new ArrayList<>();
  private List<FriendProfile> mShowFriendProfiles = new ArrayList<>();
  private List<FriendProfile> mFriendProfiles = new ArrayList<>();
  private InviteGroupMemberAdapter mAdapter;
  private ArrayList<String> mSelectIds = new ArrayList<>();

  @Override protected int getLayoutResId() {
    return R.layout.fragment_invite_group_member;
  }

  @Override protected void initPresenter() {
    presenter = new InviteGroupMemberPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    mGroupId = getArguments().getString(ID_KEY);
    mTvTitle.setText("邀请好友进群");
    mList.setLayoutManager(new LinearLayoutManager(mActivity));
    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);
    mAdapter = new InviteGroupMemberAdapter(mShowFriendProfiles, mSelectIds, mGroupMemberIds);
    mAdapter.setOnItemClickListener((adapter, view, position) -> setCheck(position));
    mList.setAdapter(mAdapter);
    getFriends();
    presenter.getGroupMembers(mGroupId);
  }

  @OnClick({ R.id.iv_back, R.id.iv_clear, R.id.btn_confirm }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.iv_clear:
        mEtSearch.setText("");
        break;
      case R.id.btn_confirm:
        confirm();
        break;
    }
  }

  @OnTextChanged(value = R.id.et_search, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
  void afterTextChanged(Editable content) {
    if (TextUtils.isEmpty(content.toString())) {
      mIvClear.setVisibility(View.GONE);
    } else {
      mIvClear.setVisibility(View.VISIBLE);
    }
    search(content.toString());
  }

  /**
   * @param position 点击的position
   * 修改选择状态
   */
  private void setCheck(int position) {

    if (mShowFriendProfiles.get(position).getIdentify()
        .equals(MyApplication.getInstance().getThirdAccId())
        || mShowFriendProfiles.get(position).getIdentify().equals(MyApplication.getInstance().getUserInfo().getQqServiceName())
        || mShowFriendProfiles.get(position).getIdentify().equals(MyApplication.getInstance().getUserInfo().getQqFeedBackName())
        || mGroupMemberIds.contains(mShowFriendProfiles.get(position).getIdentify())
        ) {
      return;
    }

    if (mSelectIds.contains(mShowFriendProfiles.get(position).getIdentify())) {
      mSelectIds.remove(mShowFriendProfiles.get(position).getIdentify());
    } else {
      mSelectIds.add(mShowFriendProfiles.get(position).getIdentify());
    }
    mAdapter.setSelectIds(mSelectIds, position);
    if (mSelectIds.size() > 0) {
      mBtnConfirm.setEnabled(true);
    } else {
      mBtnConfirm.setEnabled(false);
    }
  }

  /**
   * 好友搜索
   *
   * @param content 搜索内容
   */
  private void search(String content) {
    mShowFriendProfiles.clear();
    if (TextUtils.isEmpty(content)) {
      mShowFriendProfiles.addAll(mFriendProfiles);
      mTvEmptyTip.setVisibility(View.GONE);
      mList.setVisibility(View.VISIBLE);
    } else {
      for (FriendProfile profile : mFriendProfiles) {
        if (profile.getIdentify().contains(content)
            || profile.getName().contains(content)
            || profile.getNickName().contains(content)
            || profile.getRemark().contains(content)) {
          mShowFriendProfiles.add(profile);
        }
      }
      if (mShowFriendProfiles.size() == 0) {
        mTvEmptyTip.setVisibility(View.VISIBLE);
        mList.setVisibility(View.GONE);
      } else {
        mTvEmptyTip.setVisibility(View.GONE);
        mList.setVisibility(View.VISIBLE);
      }
    }
    mAdapter.notifyDataSetChanged();
  }

  /**
   * 获取好友列表
   */
  private void getFriends() {
    mShowFriendProfiles.clear();
    Map<String, List<FriendProfile>> friends = FriendshipInfo.getInstance().getFriends();
    List<String> groupNames = FriendshipInfo.getInstance().getGroups();
    for (String groupName : groupNames) {
      for (FriendProfile friendProfile : friends.get(groupName)) {
        mShowFriendProfiles.add(friendProfile);
        mFriendProfiles.add(friendProfile);
      }
    }
    mAdapter.notifyDataSetChanged();
  }

  /**
   * 选择完成，确定邀请
   */
  private void confirm() {
    showLoadingDialog();
    TIMGroupManagerExt.getInstance().inviteGroupMember(mGroupId, mSelectIds,
        new TIMValueCallBack<List<TIMGroupMemberResult>>() {
          @Override public void onError(int i, String s) {
            showToast("邀请失败，请稍后再试～");
            cancelLoadingDialog();
          }

          @Override public void onSuccess(List<TIMGroupMemberResult> timGroupMemberResults) {
            cancelLoadingDialog();
            setFragmentResult(RESULT_OK, new Intent());
            popBackStack();
          }
        });
  }

  @Override public void showMemberInfo(List<TIMGroupMemberInfo> timGroupMemberInfos) {
    mGroupMemberIds.clear();
    for (TIMGroupMemberInfo info : timGroupMemberInfos)
      mGroupMemberIds.add(info.getUser());
    mAdapter.notifyDataSetChanged();
  }
}
